package ece1779.ec2;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import com.amazonaws.services.cloudwatch.model.ListMetricsRequest;
import com.amazonaws.services.cloudwatch.model.ListMetricsResult;
import com.amazonaws.services.cloudwatch.model.Metric;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
import com.amazonaws.services.ec2.model.TerminateInstancesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing;
import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient;
import com.amazonaws.services.elasticloadbalancing.model.*;




///////////////////////////////////////////////////////
// stopInstance is only called with a HTTP request/////
//////////////////////////////////////////////////////
public class StopInstance extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Env Variables</title>");
        out.println("</head>");
        out.println("<body>");
		// getQueryString can get the string after the ? of a URL
		// eg http://servername/webname/pagename.csp?paramName=paramValue, the query string would be paramName=paramValue.
        ec2example(out, request.getQueryString());
        
        out.println("</body>");
        out.println("</html>");
    }
    
    
    void ec2example(PrintWriter out, String instanceId) throws IOException {
        /*
         * Important: Be sure to fill in your AWS access credentials in the
         *            AwsCredentials.properties file before you try to run this
         *            sample.
         * http://aws.amazon.com/security-credentials
         */
    	
    	
    	BasicAWSCredentials awsCredentials = (BasicAWSCredentials)getServletContext().getAttribute("AWSCredentials");
    	AmazonElasticLoadBalancing elasticLoadBalancer = new AmazonElasticLoadBalancingClient(awsCredentials);
    	
        AmazonEC2 ec2 = new AmazonEC2Client(awsCredentials);
        
        try {
        	// now we first need to remove this instance from load balancer
            String lbName = "ShengLoadBalancer";
            com.amazonaws.services.elasticloadbalancing.model.Instance lbInstance = new com.amazonaws.services.elasticloadbalancing.model.Instance(instanceId);
            List <com.amazonaws.services.elasticloadbalancing.model.Instance> lbInstances = Arrays.asList(lbInstance);
            DeregisterInstancesFromLoadBalancerRequest deregisterRequest = new DeregisterInstancesFromLoadBalancerRequest(lbName,lbInstances);
            DeregisterInstancesFromLoadBalancerResult deregisterResult = elasticLoadBalancer.deregisterInstancesFromLoadBalancer(deregisterRequest);
            
            
			// declare a list of instanceIds since terminateinstancerequest only takes list
			List <String> instanceIds = Arrays.asList(instanceId);
            TerminateInstancesRequest request = new TerminateInstancesRequest(instanceIds);
            TerminateInstancesResult result = ec2.terminateInstances(request);
            
            
            
            
            
            out.println(result.toString());
        	out.println("instance"+instanceId+"has been terminated");
        	out.println("Deregistered from Load Balancer:"+deregisterResult.toString());
        	
         
        } catch (AmazonClientException ace) {
            out.println("Caught an AmazonClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with EC2, "
                    + "such as not being able to access the network.");
            out.println("Error Message: " + ace.getMessage());
        }
    }
    
}